package com.kyzh.core.pager.weal.accountbuy


import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.fragment.app.Fragment
import com.gushenge.core.base.fragment.BaseFragment
import com.gushenge.core.impls.UserImpl
import com.gushenge.core.listeners.ResultListener
import com.kyzh.core.R
import kotlinx.android.synthetic.main.fragment_retrieve_password.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.jetbrains.anko.support.v4.runOnUiThread
import org.jetbrains.anko.support.v4.toast

/**
 * A simple [Fragment] subclass.
 */
class RetrievePasswordFragment : BaseFragment(), ResultListener {
    var time: Job? = null
    private var sessionId = ""
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        val view = inflater.inflate(R.layout.fragment_retrieve_password, container, false)
        val findViewById = view.findViewById<ImageView>(R.id.close)
        val type = arguments?.getInt("type")
        if(type==0){
            before.visibility = View.VISIBLE
            after.visibility = View.GONE
        }
        findViewById.setOnClickListener {
            activity?.onBackPressed()
            before.visibility = View.VISIBLE
            after.visibility = View.GONE
        }
        return view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        initView()
    }

    private fun initView() {
        before.visibility = View.VISIBLE
        after.visibility = View.GONE

        clPhone.setOnClickListener {
            initAfter(true)
        }
        clEmail.setOnClickListener {
            initAfter(false)
        }
    }

    private fun initAfter(b: Boolean) {
        before.visibility = View.GONE
        after.visibility = View.VISIBLE
        if (b) {
            titleView.setText(getString(R.string.verifyByPhone))
            phoneTip.text = getString(R.string.phoneNum)
            phone.hint = getString(R.string.pleaseInputPhoneNum)
        } else {
            titleView.setText(getString(R.string.verifyByEmail))
            phoneTip.text = getString(R.string.email)
            phone.hint = getString(R.string.pleaseInputEmail)
        }
        get.setOnClickListener {
            if (b) {
                UserImpl.getRegCode(phone.text.toString(), 1, this@RetrievePasswordFragment)
            } else {
                UserImpl.emailCode(phone.text.toString(), 1, this@RetrievePasswordFragment)
            }
        }
        commit.setOnClickListener {
            val phone1 = phone.text.toString()
            val code1 = code.text.toString()
            val pass = etpass.text.toString()
            if (phone1.isNotEmpty()) {
                if (code1.isNotEmpty()) {
                    if (pass.isNotEmpty()) {
                        if (b) {
                            UserImpl.retrievePassword(phone1, null, code1, sessionId, pass, this@RetrievePasswordFragment)
                        } else {
                            UserImpl.retrievePassword(null, phone1, code1, sessionId, pass, this@RetrievePasswordFragment)
                        }
                    } else {
                        toast(getString(R.string.passwordIsNotEmpty))
                    }
                } else {
                    toast(getString(R.string.verifyCodeNotNull))
                }
            }
        }
    }

    override fun success() {
        requireActivity().finish()
    }

    override fun success(bean: Any) {
        (bean as? String)?.let {
            sessionId = it
            get.isClickable = false
            time = GlobalScope.launch {
                repeat(60) { time ->
                    val sec = 59 - time
                    if (sec == 0) {
                        val msg = Message()
                        msg.what = 1
                        handler.sendMessage(msg)
                    } else {
                        runOnUiThread { get.text = "${sec}${getString(R.string.countdown)}" }
                    }
                    delay(1000)
                }
            }
        }
    }

    override fun error(error: String) {
        toast(error)
    }

    @SuppressLint("HandlerLeak")
    private val handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                1 -> {
                    get.text = getString(R.string.getVerifyCode)
                    get.isClickable = true
                    time?.cancel()
                }
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        time?.cancel()
    }
}
